<?php
use think\Db;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
function get_client_ip(){
		$ip = "unknown";
		if($_SERVER['REMOTE_ADDR'])
		{
		  $cip = $_SERVER['REMOTE_ADDR'];
		}else if(getenv("REMOTE_ADDR"))
		{
		   $cip = getenv("REMOTE_ADDR");
		}
		return $cip;
	}
//二进制转图片image/png
function data_uri($contents, $mime)
{
    $base64   = base64_encode($contents);
    return ('data:' . $mime . ';base64,' . $base64);
}
function api_notice_increment($url, $post_data){
 	$curl = curl_init();
      //设置抓取的url
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($curl, CURLOPT_URL,$url);
     //设置头文件的信息作为数据流输出
     curl_setopt($curl, CURLOPT_HEADER, 1);
      //设置获取的信息以文件流的形式返回，而不是直接输出。
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     //设置post方式提交
     curl_setopt($curl, CURLOPT_POST, 1);
     curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
     //执行命令
      $res = curl_exec($curl);
	   if( curl_errno($curl) ){
	   	 var_dump( curl_error($curl) );
	   }
   	   curl_close( $curl );
		return $res;
  }
//根据付款吗判断是微信还是支付宝
/*
 * 支付宝25~30开头的长度为16~24位的数字
 * 微信18位纯数字，以10、11、12、13、14、15开头）
 */
function get_bartype($bar){
	$begin=substr($bar,0,2);
	if($begin>20){
		return 3;
	}else{
		return 2;
	}
}
function NumToStr($num){ 
    if (stripos($num,'e')===false) return $num; 
    $num = trim(preg_replace('/[=\'"]/','',$num,1),'"');//出现科学计数法，还原成字符串 
    $result = ""; 
    while ($num > 0){ 
        $v = $num - floor($num / 10)*10; 
        $num = floor($num / 10); 
        $result   =   $v . $result; 
    }
    return $result; 
}
function get_user_no($user_id){
	$id=sprintf("%06d",$user_id);
	include_once ('./extend/code.php');	
	$code = new Code(); 
	$b = $code->encodeID(rand(1000,9999),4);
	$m = $code->encodeID(rand(1000,9999),4); 
	$e = $code->encodeID($id,4);
	return "$b $m $e";	
}
/*条码支付
 *$param $app  商户号
 * $param $key 商户 密匙
 * $op  商户收银员号
 * $amount 顶大价格
 * $channel 支付方式1支付宝2微信
 * $local_order_no 订单号
 * $notify_url="http://t1.lxtx001.com/api/index"; 回调地址
 * 
 */
function bar_pay($barcode,$app,$key,$op,$amount,$channel,$local_order_no,$notify_url='',$redirect_url=''){
	$url="http://openapi.caibaopay.com/gatewayOpen.htm?";
	$t=time();
	$notify_url=$notify_url?$notify_url:config("notify_url");
	$redirect_url=$redirect_url?$redirect_url:config("redirect_url")."?order_sn=$local_order_no";
	//$amount=1;
	$amount=$amount*100;
	$pt  ="amount=$amount&app=$app&barcode=$barcode&local_order_no=$local_order_no&operator_id=$op&timestamp=$t";
	$data="amount=$amount&app=$app&barcode=$barcode&command=open.pay.barcode&local_order_no=$local_order_no&notify_url=$notify_url&operator_id=$op&redirect_url=$redirect_url&timestamp=$t";
	$pt.="&key=$key";
	$sign=bin2hex(md5($pt,true));//md5($pt);
	$url.=$data."&sign=$sign";
	$res=file_get_contents($url);
	file_put_contents("a.txt", $res);
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	$result=$array1['data'];
	$result=get_object_vars($result);
	return $result['orderStatus'];
	
}
function is_https() {
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        return true;
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}

function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}
//自定义分享设置
function share_config(){
	$appid=config('wxpay_appid');
	$jsapiTicket = getTicket();
	$nonceStr = createNonceStr(16);
	$timestamp = time();
	$url = input("url");//'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	$string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
	$signature = sha1($string1);
	return json(['url'=>$url,'jsapi_ticket'=>$jsapiTicket,'appId'=>$appid,'nonceStr'=>$nonceStr,'timestamp'=>$timestamp,'signature'=>$signature]);
}

//获取维系分享票证
function getTicket(){
	$access_token = getToken();
	$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
	$weixin =  file_get_contents($url);
	$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
	$array = get_object_vars($jsondecode);//转换成数组
	return $array['ticket'];
}


//获取token
function getToken(){
	$appid=config('wxpay_appid');
	$appsecret=config('wxpay_appsercet');
	$rurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
	$weixin =  file_get_contents($rurl);
	$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
	$array = get_object_vars($jsondecode);//转换成数组
	if($array['access_token']){
		$record = array();
		$record['token'] = $array['access_token'];
		$record['expire'] = time() + 7000;
		// cache('access_token', $record, $record['expire']);
		return $array['access_token'];
	}else{
		return json(['code'=>406,'msg'=>'获取微信公众号授权失败！错误代码:'.$array['errcode']]);
	}
	
}


 /*
      * 
      *导入 
      * */
 function dr($fileName){
    		move_uploaded_file($_FILES['myfile']['tmp_name'],$fileName);
			$hand = fopen("$fileName","r");
			$arr_sql=array();
			while ($data = fgetcsv ($hand, 1000, ",")) {
			$sql="";
				$num = count ($data);
					for ($c=0; $c < $num; $c++) {
						$data[$c] = mb_convert_encoding($data[$c], "UTF-8", "GBK");
						if($c==$num-1)
						{
							$sql=$sql.$data[$c];
							break;
						}
						$sql=$sql.$data[$c].",";
					}
				array_push($arr_sql,$sql);
			}
    	return $arr_sql;
    	
    } 
/* 
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}

//获得全局access_token
function get_token(){
	$appid=config('wxpay_appid');
	$appsecret=config('wxpay_appsercet');
	$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
    $ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    if( curl_errno($ch) ){
   	 var_dump( curl_error($ch) );
    }
    curl_close( $ch );
    $arr = json_decode($res, true);
    return $arr['access_token'];
}

//推送模板信息    参数：发送给谁的openid,客户姓名，客户电话，推荐楼盘（参数自定）
function sendMessage($openid,$temp_id,$data,$redirect="") {
	$token = get_token();
	$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
	//发送的模板信息(微信要求json格式，这里为数组（方便添加变量）格式，然后转为json)
	$post_data = array(
		"touser"=>$openid,
		//微信后台的模板信息id
		"template_id"=>$temp_id,
		"url"=>$redirect,
		"data"=>$data,
	 );
    $post_data = json_encode($post_data);
    $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	$data = curl_exec($ch);
	curl_close($ch);
	$data = json_decode($data,true); //将json数据转成数组
	return $data;
}

//获得全局access_token
function get_token1(){
	$appid = config("xcx_appid");
   	$appsecret =config("xcx_sercet");
	$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
    $ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    if( curl_errno($ch) ){
   	 var_dump( curl_error($ch) );
    }
    curl_close( $ch );
    $arr = json_decode($res, true);
    return $arr['access_token'];
}

//小程序推送模板信息    参数：发送给谁的openid,客户姓名，客户电话，推荐楼盘（参数自定）
function wxsendMessage($openid,$temp_id,$data,$form_id) {
	$token = get_token1();
	$url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$token;
	//发送的模板信息(微信要求json格式，这里为数组（方便添加变量）格式，然后转为json)
	$post_data = array(
		"touser"=>$openid,
		//微信后台的模板信息id
		"template_id"=>$temp_id,
		"form_id"=>$form_id,
		"data"=>$data,
	 );
    $post_data = json_encode($post_data);
    $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	$data = curl_exec($ch);
	curl_close($ch);
	$data = json_decode($data,true); //将json数据转成数组
	return $data;
}

	//获取行业模板信息
 function getHangye(){
 	$token =get_token();
    $url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$token;
    //请求token，get方式
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
    $data = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($data,true); //将json数据转成数组
    //return $data["access_token"];
    return $data;
 }
/*生成支付二维码
 *$param $app  商户号
 * $param $key 商户 密匙
 * $op  商户收银员号
 * $amount 顶大价格
 * $channel 支付方式1支付宝2微信
 * $local_order_no 订单号
 * $notify_url="http://t1.lxtx001.com/api/index"; 回调地址
 * 
 */

function pay_code($app,$key,$op,$amount,$channel,$local_order_no,$notify_url='',$redirect_url=''){
	$url="http://openapi.caibaopay.com/gatewayOpen.htm?";
	$t=time();
//	$app="H48007350000002";
//	$key="ac8f09abd655bdfc0345f61ddf6d658f";
//	$op="2ec6d8240578a85b0b6949b3a335f98a";
//	$local_order_no=123456789;
	$notify_url=$notify_url?$notify_url:config("notify_url");
	$redirect_url=$redirect_url?$redirect_url:config("redirect_url")."?order_sn=$local_order_no";
	// $amount=1;
	$amount=$amount*100;
	$pt  ="amount=$amount&app=$app&local_order_no=$local_order_no&operator_id=$op&timestamp=$t";
	$data="amount=$amount&app=$app&command=caibao.pay.h5&local_order_no=$local_order_no&notify_url=$notify_url&operator_id=$op&redirect_url=$redirect_url&timestamp=$t";
	$pt.="&key=$key";
	$sign=bin2hex(md5($pt,true));//md5($pt);
	$url.=$data."&sign=$sign";
    $res=file_get_contents($url);
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	$result=$array1['data'];
	$result=get_object_vars($result);
	//$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($result['qrCode']).'&margin=1&size=10';
		//$qrcode = $qrPay->create_erweima($response->qr_code);
	//echo "<img src=$qrcode />";
	return $result['url'];
	exit;
}
	
/**
 * 调用成功
 */
function toSuccess($msg='', $data='') {
		return json(['code'=>200,'msg'=>$msg,'data'=>$data]);
	}
/**
 * 调用失败
 */
function toError($code='', $msg='', $data='') {
		return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
}
	

/**
 * 生成订单号
 */
function order_create_no(){
	$year_code = array('A', 'B', 'C', 'D', 'E', 'F');
    $date_code = array('0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M','N', 'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y');
    //一共15位订单号,同一秒内重复概率1/10000000,26年一次的循环\
    $order_sn = $year_code[(intval(date('Y')) - 2010) % 6] . //年 1位
    strtoupper(dechex(date('m'))) . //月(16进制) 1位
    $date_code[intval(date('d'))] . //日 1位
    substr(time(), -5) . substr(microtime(), 2, 5) . //秒 5位 // 微秒 5位
    sprintf('%02d', rand(0, 99)); //  随机数 2位
    return $order_sn;
}
	
/**
 * 手机端调用成功
 */
function toSuccessp($msg='', $data='') {
		return jsonp(['code'=>200,'msg'=>$msg,'data'=>$data]);
	}
/**
 * 手机端调用失败
 */
function toErrorp($code='', $msg='', $data='') {
		return jsonp(['code'=>$code,'msg'=>$msg,'data'=>$data]);
	}	
	
/**
 * 返回格式化后的当前时间
 */
function now_time(){
	return date('Y-m-d H:i:s',time());
}


/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
    $counter = array_children_count($array, $pid);
    if ($counter[0] == 0)
        return false;
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid);
    }

    return $tree;
}


/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}


/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}


/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }
    return $list;
}


//日志处理


function logc($text="",$status=""){
	$list['admin_name']=session('admin_name');
	$list['u_id']=session('admin_id');
	$list['ip']=session('ip');
	$list['add_time']=now_time();
	$list['text']=$text;
	$list['status']=$status;
	return Db::name('tg_admin_log')->insert($list);
	
}


/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function load_wechat($type = '')
{
    $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
    	$config = get_config('wechat_config');
    	$config['cachepath'] = CACHE_PATH . 'wechat';
    	$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}

function load_agent_wechat($type = '',$config)
{
    $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
    	$config = get_config('wechat_config');
    	$config['cachepath'] = CACHE_PATH . 'wechat';
    	$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}
/**
 * 设置全局配置到文件
 *
 * @param $key
 * @param $value
 * @return boolean
 */
function sys_config_setbykey($key, $value)
{
    $file = ROOT_PATH.'application/extra/log.php';
    $cfg = array();
    if (file_exists($file)) {
        $cfg = include $file;
    }
    $item = explode('.', $key);
    switch (count($item)) {
        case 1:
            $cfg[$item[0]] = $value;
            break;
        case 2:
            $cfg[$item[0]][$item[1]] = $value;
            break;
    }
    return file_put_contents($file, "<?php\nreturn " . var_export($cfg, true) . ";");
}
/**
 * 设置全局配置到文件
 *
 * @param array
 * @return boolean
 */
function sys_config_setbyarr($data)
{
    $file = ROOT_PATH.'application/extra/log.php';
    if(file_exists($file)){
        $configs=include $file;
    }else {
        $configs=array();
    }
    $configs=array_merge($configs,$data);
    return file_put_contents($file, "<?php\treturn " . var_export($configs, true) . ";");
}
/**
 * 获取全局配置
 *
 * @param $key
 * @return array|null
 */
function sys_config_get($key)
{
    $file = ROOT_PATH.'application/extra/log.php';
    $cfg = array();
    if (file_exists($file)) {
        $cfg = (include $file);
    }
    return isset($cfg[$key]) ? $cfg[$key] : null;
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query(){
	$param = request()->except(['s']);
	$rst = array();
	foreach($param as $k=>$v){
		if(!empty($v)){
			$rst[$k] = $v;
		}
	}
	return $rst;
}


/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author rainfer <81818832@qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}



/**
 * 获得配置,已oem_id 区分,获取商家、用户、龙信分佣
 */
function get_config($name,$oem_id=1){
	$where['name'] = $name;
	$where['oem_id'] = $oem_id;
	$site_config = db('tg_admin_system')->field('value')->where($where)->find();
    $site_config =unserialize($site_config['value']);
	return $site_config;
}

/**
 * 获得配置,获取省、市、区代理分佣
 */
function get_oem($oem_id){
	$where['id'] = $oem_id;
	$oem_bili = db('info_oem')->where($where)->value('oem_bili');
	return $oem_bili;
}

/**
 * 获得配置,获取专员分佣
 */
function get_sc($sc_id){
	$where['id'] = $sc_id;
	$sc_bili = db('info_user')->field('sc_bili')->where($where)->value('sc_bili');
	return $sc_bili;
}

function sendsms($sign,$mobile,$tempid,$name,$value,$oem_id=1){
	$cut_time = now_time();
	include_once ('./extend/smsapi/smsDemo.php');
	$msg=sendMess($sign,$mobile,$tempid,$name,$value,$oem_id);
	if($msg->Message=="OK") {
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['message'] 	= '发送成功';
		db('sms_code')->insert($data);
		return true;
	}else{
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['result'] 	= 0;
		$data['message'] 	= '发送失败:'.$msg->Message;
		db('sms_code')->insert($data);
		$err=$msg->Message;
		return false;
	}
}
/**
 * 短信发送
 * $mobile 手机号
 * $tempalte 短信模板ID
 * $params 参数
 */
function send_sms($mobile, $template_id, $params, $sign_name,$content=null){
	// 获取短信配置
	$sms_config = get_config('sms_config');
	include_once ('./vendor/alidayu/TopSdk.php');
    date_default_timezone_set('Asia/Shanghai');
	$c = new TopClient;
//	$c -> format = 'json';
//	$c -> simplify = true;
	$c -> appkey = $sms_config['app_key'];
	$c -> secretKey = $sms_config['app_secret'];
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req -> setSmsType("normal");
	if($sign_name){
		$req -> setSmsFreeSignName($sign_name);
	}else{
		$req->setSmsFreeSignName("龙信天下");
	}
	if($params){
		$req -> setSmsParam($params);
	}
	$req -> setRecNum($mobile);
	if($content){
		$req->setSmsParam('{"customer":"'.$content.'"}');
	}
	$req -> setSmsTemplateCode($template_id);
	$resp = $c -> execute($req);
	return $resp;
}

//根据设置名字获取设置
function getDisbution($name){
	if (cache('setting')&&isset(cache('setting')[$name])) {
		$site_config = cache('setting')[$name];
	} else {
		$site_config = db("mall_setting")->where("inc_type",$name)->find();
		$setting[$name]=$site_config;
		cache("setting",$setting);
	}
	return iunserializer($site_config['value']);
}

/**验证码*/
 function check_sendcode($mobile, $code, $message){
		$where['mobile'] = $mobile;
		$where['code'] = $code;
		$where['message'] = '发送成功';
		$result =db('sms_code')->where($where)->find();
		// 10分钟有效期
		if(time() - strtotime($result['add_time']) > 600){
			return 2;
		}
		if($code == $result['code']){
			return 1;
		}else{
			return -1;
		}
	}
	
	/**
	 * 发送短信验证
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	function get_code($mobile){
		// 获取短信模板
		$tem_w['title']='用户注册';
		
		$template = db("sms_template")->where($tem_w)->find();
		// 如果是验证码类型，则生成6位验证码
		if($template['type'] == 1){
			$code = rand(100000, 999999);
			$template['params'] = str_replace('${code}', $code, $template['params']);
			$data['code'] = $code;
		}
		$msg=sendsms($template['sign_name'],$mobile,$template['tid'],'code',$code,1);
		
		if($msg){
			return json(["code"=>200,"msg"=>'发送成功!']); 
		}else{
			return json(["code"=>408,"msg"=>'发送失败']); 
		}
	}
	
	//判断是微信还是支付波啊打开1支付宝2微信
	function get_brower_type(){
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			return 2;
		}elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
			return 1;
		}
		return 0;
	}
	/**
	 * 获取支付宝key
	 * 支付宝请求秘钥$aliy_key
	 */
	function user_ali_id($aliy_key){
		import("payment.dpay.aop.AopClient");
		import("payment.dpay.aop.request.AlipaySystemOauthTokenRequest");
		$code = $aliy_key;//获取code
		$aop = new \AopClient ();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = config('alipay_appid');
		$aop->rsaPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCICVD9KshbDmry/eW0Ut+0m+MIU2c7whGcWR1pszi34Fe3gURl6f4vYQrQKImzDuBOeWPfKIO7ccTnPl8vv9WJzv6AkxTfbadW2GYFqf5mZSIr2S/+wL/HAGaJeFtl2nT0DNLVwCZw1z8L9W3hQmWU+VRDhRvKdjVooh3gMfLjXyQGL5HmI+2YMIehEr4Av3MU6GhyTfHgE8PyP3DS3X8Doo+ZJEu2IHg9eT8BkLMFG60u+igA58PUI7fxbvdKoU6OGZwbLhCouIDbOncU+RAaBzyDeOfVjBuZY4LFhGNluP7TOuPo45IvDXXEltL1PsSz5ZAOlgJiN7fiLe5aqULAgMBAAECggEAR+NWcxqCSG6v1bdTSyDJYoEDWxky9ZYgrjoK0+yYmGX95NknV7a+925LzFFiw6hk31mK9yBVr4WxS6aXNlGWYpQ+UDpgzGdRMdHAMvOhTQWJx5GOSXl1CFcCk5SF27OgpYIKNH8WN9x0TGZo3YBD8abbs1Hh/B/USQIH/m1I86ycrkVprQIYP6z//RwNRw+BkMze06nx4rlleS9/ral1F4y33Ej2P2xGsbkEKcJsa+MnEf+a9uPYWqxNdKWePQIlA5zqPxJEhnUYgxBTDlSNj+5vAaeQDY3IIui5XmlVRDdBvDj5JEUC9sBCE6UgYWO08c0qEQJWbTY0ZLpazICxoQKBgQD7OUnqqzeky8w6Q0/7FN9FcXHs3d1fNhsnEiqgVDo4+cGSCZsBV+yLjTG8lN6MWpV5mlocGLt8kJSlz37oeWML3xYhskjSFliguyY4i0xUpMPPPQgHSv6IOA/JbkZ9xjy1udDM3/B/ke6efI/0QYvwKBm8QLnv+8Hi+ZXTBBG2gwKBgQCEmXgnqe11i45TNRmuZl2C3tTBXIdcbk0vcGWNoiM/vsqa5REn0DqsACL532FdkCSk8SfFNsFm2bbq6Mz6X3agyJ3Hl6E8gCLzEM7bv/wmUpLf9LJ4sjMMJNmtFmgtp0auIAkglixd8xCO/ymGNDay8oBevcF9HQgCK54iPspQ2QKBgQC3iATOIcOG6zQKJH7byUXLr7Mw/mzpT9fKVWU6uA3I7f1SOR46fwdadA4v3Poww0SMEA1glVjzCZTvBYWLRJLta0750wuMH7MjyVWE3Y8oDy7VyZqB6XHGBl7SI3PwEtDrWhKGedty9yPCOPHZ2cDn9APJGeg8wEnHDds8y649DQKBgCyumnKjLEVj1X3scs7156Tl+cN+ro5TDOdjdJUZgc9FN3iin/lOjbbQBPk2cNTacb6zFLe8D8fcrWrTL99es9bSQ3iye76rXxuRGmOqeglf4eZdypYpVlJNSJyu5EQeDg829FxqvmCaO4Y0LYXvqk76sI88WisS0VQJ5qubhQlhAoGAAW+DD0RuKPxMviSENCZNQau7YMFFlfMC7xY8godHzg9nCEmt6Wuu8z3TD2bbeQx+wd3VCHcT5/Y6cEkexn0lM+7vWNcZgk6J3EzgIumV8KcLGbLZX97bE+Nwjk6gAxt3gMGslI+CIe5B0wG0CqWQwTHXBPDLBmEBOveSrIo9anw=";
		$aop->alipayrsaPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjkJlBPWQkWe+ExtL1z2XMIjsvOwvduz1CVKgxlwfPGbzzBVsmXzEjdnIjHpF6KjGo8MwaGd9wRmsVM3kqMvuHDbBfk4egoKClgzXLYPuUrNK6h5bsz6WY1/8tBlg2xMVg2AabNdHSEwI8z6PDELcfVmkkcOfS+fGzuCnvSYeEIpGzz1uQQPSbHfxNxCcCdkJ0SZfjduX2augFZ+1L/sorJgLxfNxWBcNCyJST1M3Eix5NHOA6iR3iSvkV4z0Yes1uMyv4Rp3nHFs8KMOZOsTmrqvpLWrhEkz7EH5j+v7fjRVmgb42Whz3HxP9tuhDgFC7YpbCfKURZZFqWYUTpTLvQIDAQAB";
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		
		$request = new \AlipaySystemOauthTokenRequest ();
		$request->setGrantType("authorization_code");
		$request->setCode($code);
		$result = $aop->execute ( $request); 
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->user_id;
		
		return  $resultCode;
	}
	function union_id($aliy_key){
		$code = input("code");//获取code
		$curl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wxpay_appid')."&secret=".config('wxpay_appsercet')."&code=$code&grant_type=authorization_code";
		$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$access_token=$array['access_token'];
		$openid = $array['openid'];//输出openid
		$data['openid']=$openid; 
		$url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
		$weixin =  file_get_contents($url);//通过code换取网页授权access_token
		file_put_contents("lx.txt", $weixin);
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$data['nick_name']=$array['nickname'];
		$data['headimgurl']=$array['headimgurl'];
		$data['unionid']=$array['unionid'];
		return $data;

	}
	function user_wx_id1($aliy_key){
		$code = input("code");//获取code
		$curl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wxpay_appid')."&secret=".config('wxpay_appsercet')."&code=$code&grant_type=authorization_code";
		$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
	    $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$access_token=$array['access_token'];
		$openid = $array['openid'];//输出openid
		$data['openid']=$openid; 
		$url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
		$weixin =  file_get_contents($url);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$data['nickname']=$array['nickname'];
		$data['logo']=$array['headimgurl'];
		
		return $data;
		}
	//获取openid
	function user_wx_id($aliy_key){
		$we_config = get_config('payment_config');
		$code = input("code");//获取code
		$curl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wxpay_appid')."&secret=".config('wxpay_appsercet')."&code=$code&grant_type=authorization_code";
		$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$openid = $array['openid'];//输出openid
		return $openid;
	}

	//获取小程序openid 
	function wx_openid(){
		$code = input("code");//获取code
		$appid=input("appid");
		$secret=input("secret");
		$curl="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$openid = $array['openid'];//输出openid
		return $openid;
	}
//oem资金变化日志
    function balance_change($order_type,$balance,$message,$oem_id){
    	$data['order_type'] = $order_type;
    	$data['balance'] 	= $balance;
    	$data['message'] 	= $message;
    	$data['oem_id'] 	= $oem_id;
    	$data['add_time'] 	= now_time();
    	$res=db('log_oem_charge')->insert($data);
		return $res;
    }
	//平台鼓励金变化日志
    function admin_charge($balance,$type,$user_id,$agent_id,$message){
    	$data['add_time'] 	= now_time();
    	$data['balance'] = $balance;
    	$data['type'] 	= $type;
    	$data['user_id'] 	= $user_id;
    	$data['agent_id'] 	= $agent_id;
    	$data['message'] 	= $message;
    	$res=db('admin_charge')->insert($data);
		return $res;
    }
	//oem佣金变化日志
    function oem_score_change($order_type,$balance,$message,$oem_id,$skr=0,$type=0){
    	$data['order_type'] = $order_type;
    	$data['balance'] 	= $balance;
    	$data['message'] 	= $message;
    	$data['oem_id'] 	= $oem_id;
		$data['add_time'] 	= now_time();
		$data['skr'] 	= $skr;	    
		$data['type'] 	= $type;
		$res=db('log_oem_score')->insert($data);
		return $res;
    }
  	//oem佣金变化日志
    function commission_change($order_type,$balance,$message,$oem_id){
    	$data['order_type'] = $order_type;
    	$data['balance'] 	= $balance;
    	$data['message'] 	= $message;
    	$data['oem_id'] 	= $oem_id;
    	$data['add_time'] 	= now_time();    	
    	$res=db('log_oem_commission')->insert($data);
		return $res;
    }
    
    //用户,商家申请提现日志
    function withdrawals_log($user_id,$user_type,$balance,$actual_balance,$money_charge_id){
    	if($user_type == 1){
    		//获取当前商户信息
    		$user_info 	 = db('info_agent')->where('id',$user_id)->find();
    		//获取认证信息
    		$agent_qianyue = db('agent_qianyue')->where('agent_id',$user_id)->find();
    		$data['bank_account'] 	= $agent_qianyue['open_bank'];
	    	$data['bank_no'] 		= $agent_qianyue['bank_account'];
	    	$data['bank_username'] 	= $agent_qianyue['account_name'];
	    	$data['bank_mobile'] 	= $agent_qianyue['yl_mobile'];
	    	
    	}else{
    		 //获取当前用户信息
    		$user_info 	 = db('info_user')->where('id',$user_id)->find();
    		$user_verify = db('sys_member_verif')->where('user_id',$user_id)->where('user_type',1)->find();
    		$data['bank_account'] 	= $user_verify['bank_name'];
	    	$data['bank_no'] 		= $user_verify['bank_no'];
	    	$data['bank_username'] 	= $user_verify['user_name'];
	    	$data['bank_mobile'] 	= $user_verify['reserve_mobile'];
    	}
    	
    	$data['user_id'] 		 = $user_info['id'];
    	$data['user_type'] 		 = $user_type;
    	$data['balance'] 		 = $balance;
    	$data['actual_balance']  = $actual_balance;
    	$data['money_charge_id'] = $money_charge_id;
    	$data['cash_state'] 	 = 1;
    	$data['create_time'] 	 = now_time();
    	$data['oem_id'] 		 = $user_info['oem_id'];
    	
    	return db('user_withdrawals')->insert($data);
    }
    
    
    //oem 提现
    function oem_withdrawals_log($oem_id,$balance,$actual_balance,$money_charge_id){
    	//获取oem信息
    	$oem_info = db('info_oem')->where('id',$oem_id)->find();
    	//获取oem认证信息
    	$user_verify = db('sys_member_verif')->where('user_id',$oem_id)->where('user_type',2)->find();

    	$data['oem_id'] 		= $oem_info['id'];
	    $data['balance'] 		= $balance;
	    $data['actual_balance'] = $actual_balance;
	    $data['cash_state'] 	= 1;
    	$data['bank_account'] 	= $user_verify['bank_name'];
    	$data['bank_no'] 		= $user_verify['bank_no'];
    	$data['bank_username'] 	= $user_verify['user_name'];
    	$data['bank_mobile'] 	= $user_verify['reserve_mobile'];
    	$data['money_charge_id'] = $money_charge_id;
    	$data['create_time'] 	= now_time();
    	
    	return db('oem_withdrawals')->insert($data);
    	
    }
    
    //用户佣金变化日志
	function user_commission_change($u_id,$order_sn,$order_type,$balance,$operator,
	$message,$pay_type,$oem_id,$agency_id,$city_id){
		$data['u_id'] 			= $u_id;
		$data['order_sn'] 		= $order_sn;
		$data['order_type'] 	= $order_type;
		$data['balance'] 		= $balance;
		$data['operator'] 		= $operator;
		$data['message'] 		= $message;
		$data['pay_type'] 		= $pay_type;
		$data['oem_id'] 		= $oem_id;
		$data['agency_id'] 		= $agency_id;
		$data['city_id'] 		= $city_id;
		$data['add_time'] 		= now_time();
    	return db('log_user_commission')->insert($data);
	}

	function user_score_change($u_id,$order_type,$balance,
	$message,$zz_user_id=0,$sk_user_id=0,$new_user_id=0){
		$data['u_id'] 			= $u_id;
		$data['order_type'] 	= $order_type;
		$data['balance'] 		= $balance;
		$data['message'] 		= $message;
		$data['add_time'] 		= now_time();   
		$data['zz_user_id'] 		= $zz_user_id;
		$data['sk_user_id'] 		= $sk_user_id;
		$data['new_user_id']=$new_user_id;
		return db('log_user_score')->insert($data);
	}
	
	
	//用户余额变化日志
	function user_money_change($u_id,$order_type,$balance,$message){
		$data['u_id'] 			 = $u_id;
		$data['order_type'] 	 = $order_type;
		$data['balance'] 		 = $balance;
		$data['message'] 		 = $message;
		$data['add_time'] 		 = now_time();
		return db('log_user_charge')->insertGetId($data);
	}

	//商家鼓励金变化日志
	function agent_score_change($agent_id,$order_type,$chain_id,$clerk_id,$balance,$message){
		//获取商家信息
    	$data['agent_id'] 		= $agent_id;
		$data['chain_id'] 		= $chain_id;
		$data['clerk_id'] 		= $clerk_id;
    	$data['order_type'] 	= $order_type;
		$data['balance'] 		= $balance;
    	$data['message'] 		= $message;
    	$data['add_time'] 		= now_time();
    	return db('log_agent_score')->insert($data);
	}

	//商户资金变化日志
    function agent_money_change($agent_id,$chain_id,$clerk_id,$order_sn,$order_type,$balance,$message,$pay_type){
    	
		//获取商家信息
		$agent_info = db('info_agent')->where('id',$agent_id)->find();
		
    	$data['agent_id'] 		= $agent_info['id'];
//		$data['chain_id'] 		= $chain_id;
		$data['clerk_id'] 		= $clerk_id;
    	$data['order_sn'] 		= $order_sn;
    	$data['order_type'] 	= $order_type;
    	$data['balance']		= $balance;
    	$data['message'] 		= $message;
    	$data['pay_type'] 		= $pay_type;
//  	$data['oem_id'] 		= $agent_info['oem_id'];
//  	$data['agency_id'] 		= $agent_info['agency_id1'];
//  	$data['city_id'] 		= $agent_info['agency_id2'];
//		$data['salesman_id']	= $agent_info['salesman_id'];
    	$data['add_time'] 		= now_time();
    	return db('log_agent_charge')->insertGetId($data);
	}
	
	//添加日志
	function add_log($goods_num,$goods_id,$user_id,$agent_id,$chain_id,$emp_id,$sn,$pay_type,$state,$total_price,
	$pay_price,$order_type){
		$data['goods_num']=$goods_num;
		$data['goods_id']=$goods_id;
		$data['uid']=$user_id;
		$data['agent_id']=$agent_id;
		$data['chain_id']=$chain_id;
		$data['clerk_id']=$emp_id;
		$data['order_type']=$order_type;
		$data['order_sn']=$sn;
		$data['pay_type']=$pay_type;
		$data['state']=$state;
		$data['origin_price']=$total_price;
		$data['balance']=$pay_price;
		$data['add_time']=now_time();
		$data['sy_type']=3;
		$res=db('log_paylog')->insert($data);
		return $res;
	}
	//变更会员推荐商家id
	function update_level($user_id,$agent_id){
		$users=db("info_user")->where("level",$user_id)->field("id,level,tj_agent,is_agent")->select();
		foreach($users as $user){
			if($user['is_agent']!=2){
				$up['tj_agent']=$agent_id;
				$res=db('info_user')->where("id",$user['id'])->update($up);
				if($res){
					update_level($user['id'],$agent_id);
				}
			}
		}
	}
	
	//购买日志()
	function recharge_log($user_id,$balance,$order_type,$order_sn,$pay_type,$message,$oem_id,$clerk_id=0){
		//购买日志
		$credit_data = array(
			'uid'			=> $user_id,
			'balance'		=> $balance,
			'origin_price'	=> $balance,
			'order_type' 	=> $order_type,
			'order_sn' 		=> $order_sn,
			'pay_type' 		=> $pay_type,
			'state' 		=> 1,
			"message"		=> $message,
			"order_id"		=> 0,
			"oem_id"		=> $oem_id,
			'add_time' 		=> now_time(),
			'tj_clerk_id'	=>$clerk_id
		);
		$res= db('log_paylog')->insert($credit_data);
		return $res;
	}
	
	//消息推送
	function push_msg($agent_id,$money){
		include_once ('extend/JPush/autoload.php');
		 //初始化
		$app_key = "f3cf1f27b7ec64c917e5a481";
		$master_secret = "0b7e2a33ed4713b29a4c8db4";
		$client = new \JPush\Client($app_key, $master_secret);
		try{
			//简单的推送样例
		  	$pusher = $client->push();
			$pusher->setPlatform('all');
			$pusher->addAllAudience(); // 设置所有设备都推送
			$pusher->setMessage("Hi", 'title', 'type', array("agent_id"=>$agent_id, "money"=>$money));
			$pusher->send();
		} catch (\JPush\Exceptions\JPushException $e) {
		    // try something else here
		    print $e;
		}
	}
	
	
	//获取用户union_id 
	function is_atten($info_user){
		$openid=$info_user['openid'];
		$appid=config('wxpay_appid');
		$secret=config('wxpay_appsercet');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
		$res=file_get_contents($url);
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		
		$access_token=$array1['access_token'];
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
			if(!$info_user['nickname']){
				$up['nickname']=$array1['nickname'];
			}
			if(!$info_user['logo']){
				$up['logo']=$array1['headimgurl'];	
			}
			if($info_user['is_atten']!=1){
				$up['is_atten']=1;				
			}
			if($info_user['member_level']=="ratio_one" || empty($info_user['member_level'])){
				$up['member_level']="ratio_two";				
			}
			if(!$info_user['unionid']){
				$up['unionid']=$array1['unionid'];				
			}
			if(isset($up)){
				db('info_user')->where('openid',$openid)->update($up);				
			}
			return true;
		}else{
			return false;
		}
	}

function log_type_msg($type){
	if($type == 1){
		$msg = '线上订单';
	}else if($type == 2){
		$msg = '门店收款码';
	}else if($type == 4){
		$msg = '广告充值';
	}else if($type == 5){
		$msg = '商家鼓励金充值';
	}else if($type == 6){
		$msg = '线下收银';
	}else if($type == 7){
		$msg = '线下单产品收银';
	}else if($type == 8){
		$msg = '用户鼓励金充值';
	}else if($type == 9){
		$msg = 'oem鼓励金充值';
	}else if($type == 10){
		$msg = '会员卡充值';
	}else if($type == 11){
		$msg = '会员卡消费';
	}else if($type == 12){
		$msg = '次卡购买';
	}
	return $msg ;
}


	//新用户领取奖励
	function receive(){
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false ) {
			return false;
		}
		
		//查询用户信息
		$user_id = session('info_user')['id'];
		$user=db('info_user')->where("id",$user_id)->find();

		//查询所在代理新用户所获得的鼓励金
		$oemarr['id']=$user['agency_id1'];
		$oemarr['user_level']=2;
		$score = db('info_oem')->where($oemarr)->value('s_score');
		if($user_id&&$user['is_receive']==0){
			$result = true;
			$oem=db('info_oem')->where("id",1)->find();
			if($oem){
				Db::startTrans();
				$t_score = 0;
				//推荐上级奖励
				$give_config=Db::name('tg_admin_system')->where("name","give_config")->value('value');
				$give_config = unserialize($give_config);
				if($give_config==1){
					if($user['level']){
						$t_score = $oem['tj_amount'];
						$res6 = oem_score_change(8,$t_score,"赠送新用户推荐人".$t_score."鼓励金",1,$user['level'],4);
						if(!$res6) $result = false;
						$res7 = db('info_user')->where('id', $user['level'])->setInc('score', $t_score);
					}
				}
               
				//oem扣除鼓励金
				$z_score = $score+$t_score;
				$res1 = db('info_oem')->where('id',1)->setDec('score',$z_score);
				if(!$res1) $result = false;
				
				$res2 = oem_score_change(8,$score,"赠送新用户{$score}鼓励金",1,$user_id,4);
				if(!$res2) $result = false;
				
				$res3 = db('info_user')->where('id',$user_id)->update(['is_receive'=>1]);
				if(!$res3) $result = false;
				
				$res4 = db('info_user')->where('id', $user_id)->setInc('score', $score);
				if(!$res4) $result = false;
				
				$res5 = user_score_change($user_id,'17',$score,"新用户注册送{$score}个鼓励金");
				
				if(!$res5) $result = false;
				if($result){
					Db::commit();
				}else{
					Db::rollback();
				}
			}
			
		}elseif($user['is_receive']==1){
			session('info_user.is_receive',1);
		}
	}

	function category($parent_id){
		$where['parent_id'] = $parent_id;
		$where['category_type'] = 2;
		$list = db('agent_category')->where($where)->order('category_sort','asc')->select();
		return $list;
	}

function mb_unserialize($str) {
    return preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$str);
}

function pay_api($str) {
    return preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$str);
}

function qrcode($url){
	header("Content-Type: application/json;charset=utf-8"); 
	//引入二维码生成插件 
	vendor("qrcode.phpqrcode"); 
	// 生成的二维码所在目录+文件名 
	$path = "public/static/beiquan/qrcode/";
	//生成的二维码所在目录 
	if(!file_exists($path)){ mkdir($path, 0700,true); } $time = md5(rand(1,999).time().rand(1,999)).'.png';
	//生成的二维码文件名 
	$fileName = $path.$time;
	//1.拼装生成的二维码文件路径 
	$data = $url;
	//2.生成二维码的数据(扫码显示该数据) 
	$level = 'L';
	 //3.纠错级别：L、M、Q、H  
	 $size = 10;
	 //4.点的大小：1到10,用于手机端4就可以了 
	 ob_end_clean();
	 //清空缓冲区 
	 \QRcode::png($data, $fileName, $level, $size);
	 //生成二维码 
	 //文件名转码 
	 $file_name = iconv("utf-8","gb2312",$time); 
     $qrcode = 'https://'.$_SERVER['HTTP_HOST'].'/'.$path.$file_name;
	 return $qrcode;
}